package cn.wyu.blogrest.controller;

import cn.wyu.blogrest.entity.Status;
import cn.wyu.blogrest.entity.User;
import cn.wyu.blogrest.repository.AuthRepository;
import cn.wyu.blogrest.repository.StatusRepository;
import cn.wyu.blogrest.service.StatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;

/**
 * Created by ajinlong on 2021/10/26.
 */

@RestController
@RequestMapping(value = "/status")
@Transactional
public class StatusController {
    @Autowired
    private AuthRepository authRepository;

    @Autowired
    private StatusRepository statusRepository;

    @Autowired
    private StatusService statusService;


    /**
     * 发布微博
     * @param accessToken
     * @param status
     * @return
     */

    @RequestMapping(method = RequestMethod.POST)
    public Status statusPost(@RequestHeader("accessToken") String accessToken,Status status){
        if (status.getContent().length()>0){
            User user = this.authRepository.findFirstByAccessToken(accessToken).getUser();
            status.setUser(user);
            this.statusRepository.save(status);
        }
        return  status;
    }

    /**
     * 获取一条微博
     * @param accessToken
     * @param statusId
     * @return
     */
    @RequestMapping(value = "/{statusId}",method = RequestMethod.GET)
    public Status statusGet(@RequestHeader("accessToken") String accessToken, @PathVariable int statusId){
        return  this.statusRepository.findById(statusId);
    }


    /**
     * 点赞
     */

    @RequestMapping(value = "/like/{statusId}")
    public  Status statusLike(@PathVariable int statusId){

        return  this.statusService.incLikes(statusId);
    }

    /**
     * 删除微博
     */

    @RequestMapping(value = "/{statusId}",method = RequestMethod.DELETE )
    public Status statusDestory(@PathVariable int statusId){
        Status status = this.statusRepository.findById(statusId);
        this.statusRepository.delete(status);
        return  status;
    }
}
